import {
  ArgumentsHost,
  Catch,
  ExceptionFilter,
  HttpException,
} from '@nestjs/common';

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    const status = exception.getStatus();
    const exceptionResponse: any = exception.getResponse();

    // 更好地处理异常响应格式
    let message = exception.message || 'Internal server error';

    if (typeof exceptionResponse === 'object') {
      // 处理 NestJS 默认的异常格式
      if (exceptionResponse.message) {
        if (Array.isArray(exceptionResponse.message)) {
          message = exceptionResponse.message[0];
        } else if (typeof exceptionResponse.message === 'string') {
          message = exceptionResponse.message;
        }
      } else {
        // 处理其他可能的对象格式
        message = JSON.stringify(exceptionResponse);
      }
    }

    const errorResponse = {
      data: {},
      message: message,
      code: status,
    };

    response.status(status);
    response.header('Content-Type', 'application/json; charset=utf-8');
    response.send(errorResponse);
  }
}